package com.shard.web;

import com.shard.service.TestShardService;
import io.shardingsphere.core.constant.transaction.TransactionType;
import io.shardingsphere.core.transaction.TransactionTypeHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author: LCG
 * 作者: LCG
 * 日期: 2021/4/1  8:38
 * 描述:
 */
@RestController
public class TestShardController {

    @Autowired
   TestShardService testShardService;

    /**
     * 作者: LCG
     * 日期: 2021/4/1  20:25
     * 描述: 注意ShardingJdbc的事务的实现要依靠 Transactional 和 ShardingJdbc提供的事务共同作用才可以实现
     * @Param [id]
     * @Return void
     */
    @RequestMapping("add/{id}")
    @Transactional(rollbackFor = Exception.class)
    public void test01(@PathVariable String id){
        //设置事务的实现类型
        TransactionTypeHolder.set(TransactionType.XA);
        for (int i=1;i<=5;i++){
            Map<String,Object> map=new HashMap<>();
            map.put("orderName","UUU"+new Random().nextInt(60000));
            int userid=new Random().nextInt(50);
            map.put("userId",userid);
            map.put("createTime", new Date());
            long idd=System.currentTimeMillis()+i;
            map.put("id",idd);

            for(int g=1;g<=4;g++){
                Map<String,Object> map2=new HashMap<>();
                map2.put("userId",userid);
                map2.put("id",System.currentTimeMillis()+i+g);
                map2.put("orderId",idd);
                map2.put("itemName","YYY"+new Random().nextInt(5000));

                testShardService.insertItem(map2);
            }

            testShardService.insert(map);
        }

        if (id.equals("1")){
            throw new RuntimeException("==============");
        }

    }

    @RequestMapping(value = "test02/{orderName}")
    public Object test02(@PathVariable String orderName){
        Map<String,Object> map=new HashMap<>();
        map.put("orderName",orderName);
        return testShardService.getList(map);
    }


    /**
     * 作者: LCG
     * 日期: 2021/4/1  21:01
     * 描述: 绑定表的查询
     * @Param [orderName]
     * @Return java.lang.Object
     */
    @RequestMapping(value = "test03/{orderName}")
    public Object test03(@PathVariable String orderName){
        Map<String,Object> map=new HashMap<>();
        map.put("orderName",orderName);
        return testShardService.getListOrderItem(map);
    }

}
